<template>
  <div class="juggle-gadget" :id="id">
    <Portal to="right-disable"
            v-loading="loading"
            :disabled="!queryModelDefaultSetting.showSetting">
      <el-card shadow="never"
               :style="{height: gadgetHeight + 'px',}">
        <div class="cardHeader"
             @mouseenter="mouseenter(true)"
             @mouseleave="mouseenter(false)"
             v-if="widgetName">
          <GadgetTitle :gadgetSetting="setting"
                       :widgetName="widgetName"></GadgetTitle>
          <div>

            <MoreMenu :slicer='slicer'
                      :gadgetId='id'
                      :gadgetType='gadgetInfo.com'
                      @updateQuery="query"
                      :widgetName="widgetName"
                      :businessType="gadgetInfo.businessType"
                      :id="gadgetInfo.id"
                      @showQueryModel="showQueryModel"
                      @fullScreen="fullScreen" />
          </div>
        </div>
        <ZCanvas class="flex-1 flex justify-center items-center"
                 :setting.sync="setting" />
        <ZAllocate :width="350"
                   :isStreth="isStreth"
                   :setting.sync="setting"
                   v-if="setting.type === 'widget'" />
        <Lastupdatetime v-if="currentTime"
                        :currentTime="currentTime"
                        :linkedDatasetList="linkedDatasetList"
                        :errorStatus="errorStatus"
                        @updateQuery="query()"></Lastupdatetime>
      </el-card>

    </Portal>
    <DrillThrough :gadgetId='id'
                  :pageId='pageId'
                  :slicer="slicer"
                  :queryId="queryId"
                  ref="drill-through"
                  :widgetName='widgetName' />
    <Model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           :selectFields="selectFields"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting" />
  </div>
</template>
<script>
import ZCanvas from './canvas.vue'
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import mixinFormatViewModule from '@/mixins/format-gadget-view-module'
import ZAllocate from './allocate.vue'
import Lastupdatetime from '@/components/last-update-time/index.vue'
import { get, set, omit } from 'lodash'
import Emitter from '@/mixins/emitter'

export default {
  name: 'JuggleGadget',
  components: {
    ZCanvas,
    ZAllocate,
    Lastupdatetime,
    Model: () => import('@/components/gadget/query-model/query-model')
  },
  mixins: [mixinGadgetViewModule, mixinFormatViewModule, Emitter],
  props: {
    dataInfo: {
      type: Object,
      default: () => ({})
    }

  },
  data () {
    return {
      isStreth: true,
      currentTime: null,
      loading: false,

      queryId: '',

      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'jugglegadget',
          gadgetSetting: {}
        }
      },

      selectFields: [],
      widgetName: '',
      linkedDatasetList: [],
      data: []

    }
  },

  created () {
    this.gadgetHeight = (this.gadgetInfo.h * 20) - 45
    this.$on('event:streth', (streth) => {
      this.isStreth = streth
    })
    this.subscribeMessage('runReport', this.query)
  },
  computed: {
    setting: {
      get () {
        if (this.filterType !== 'gadget') {
          return this.dataInfo.gadgetSetting
        }
        return this.queryModelDefaultSetting.dataInfo.gadgetSetting
      },
      set (val) {
        this.dispatch('QueryModel', 'event:setting', { ...val, type: this.filterType })
        this.queryModelDefaultSetting.dataInfo.gadgetSetting = { ...val, type: this.filterType }
      }
    }
  },
  watch: {
    filterType: {
      handler (val) {
        this.setting.type = val
      },
      immediate: true
    },
    'setting.field' (val) {
      const cloneSources = (this.setting.sources || []).map((item, index) => {
        const field = get(item, 'props.field') || val
        set(item, ['props', 'content'], get(this.data[index], field) || item.content)
        return item
      })
      this.setting.source.field = val
      this.setting.sources = cloneSources
    }

  },
  methods: {
    setHeight () {
      document.querySelector('.' + this.randomId + '>iframe').style.height = (this.gadgetHeight - 20) + 'px'
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    queryModelPreview () {
      this.query(true)
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },

    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight = (newH * 20) - 45
      this.gadgetWidth = newWPx
    },
    async query () {
      try {
        this.loading = true
        let tempObj = this.returnReportLinkParam()
        if (tempObj['name'] && this.slicer['name'] && tempObj['name'] === this.slicer['name']) delete this.slicer['name']
        const params = {
          ...omit(this.slicer, 'id'),
          code: this.code,
          gadgettype: this.wgadgettype,
          widgetName: this.wName,
          pageId: this.pageId,
          gadgetId: this.id,
          type: this.filterType,
          slicer: { ...this.slicer },
          filter: this.getFilterStr()
        }
        const { data: response } = await this.$interface.reports.getReportDataInfo(params)
        this.verifyHasData(response)

        if (response.code !== 0) {
          throw response.msg
        }

        this.linkedDatasetList = get(response, 'datasetSync', [])
        this.selectFields = get(response, 'selectFields', [])
        this.data = get(response, 'data', [])

        const { sources, headerDescription, field: sField, type, ...rest } = get(response, 'config', {})
        const cloneSources = (sources || []).map((item, index) => {
          const field = get(item, 'props.field') || sField
          set(item, ['props', 'content'], get(this.data[index], field) || item.content)
          return item
        })
        const config = {
          ...rest,
          field: sField,
          headerDescription: headerDescription || '',
          sources: cloneSources,
          source: cloneSources.length ? cloneSources[0] : {}
        }
        this.setting = config

        this.widgetName = get(response, 'name', get(this.setting, 'headerTitle'))
      } catch (error) {
        if (error.response && error.response.status === 504) {
          this.errorStatus = '504'
          this.gadgetMessageBus.$emit(this.pageId + 'stopautorefresh')
        }
      } finally {
        this.currentTime = new Date()
        this.loading = false
        this.updateGadgetLoadingStatus(!this.loading)
      }
    }
  },
  destroyed () {
    this.$off('event:streth')
  }
}
</script>
<style lang="scss" scoped>
.juggle-gadget {
  .el-card {
    ::v-deep .el-card__body {
      height: 100%;
      display: flex;
      flex-direction: column;
      padding: 0px !important;
      position: relative;
    }
    ::v-deep .el-divider--horizontal {
      margin: 3px 0 !important;
    }
    .cardHeader {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 6px 20px;
      border-bottom: 1px solid #eee;
      position: relative;
    }
  }
}
</style>
